package com.suning.park.admin.mgr.permissions.controller;

import com.suning.park.dto.model.FunctionSource;
import com.suning.park.admin.exception.BusinessFailException;
import com.suning.park.admin.mgr.permissions.service.FuncTreeService;
import com.suning.park.admin.util.JsonUtil;
import com.suning.park.admin.util.StringUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.admin.util.page.PageResult;
import com.suning.park.admin.base.BasicData;
import com.suning.park.admin.databasespec.model.SpecFunctionSource;
import com.suning.park.admin.enums.EnableStatusEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源管理模块接口
 * @author niecheng
 */
@Controller
@RequestMapping(value = "/mgr/funcTree")
public class FuncTreeController implements BasicData {

    private static final Logger logger = LoggerFactory.getLogger(FuncTreeController.class);

    @Resource(name = "funcTreeServiceImpl")
    protected FuncTreeService funcTreeService;



    /**
     * 资源管理列表信息查询
     * @param request
     * @param draw
     * @param pageInfo
     * @param name 资源名称
     * @return
     */
    @RequestMapping(value = "/ajaxList", method = RequestMethod.POST)
    public
    @ResponseBody
    PageResult uesrlist(HttpServletRequest request, @RequestParam(value = "draw") int draw, PageInfo pageInfo, String name) {
        logger.info("资源管理列表信息，资源名称：{}",name);
        Map<String, Object> params = new HashMap<>();
        try {
            if(StringUtils.isNotBlank(name)){
                params.put("sourceName", name.trim());
            }
            pageInfo = funcTreeService.queryByPage(params, pageInfo);
        } catch (BusinessFailException se) {
            logger.error("资源管理列表信息 业务异常, 失败信息：{}，资源名称：{}", new Object[]{se.getMessage(), name});
            return null;
        } catch (Exception e) {
            logger.error("资源管理列表信息 程序异常, 失败信息：{}, 资源名称：{}", new Object[]{e.getMessage(), name});
            return null;
        }
        return new PageResult(pageInfo, draw);
    }



    /**
     * 异步获取所有资源信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getAuFuncTrees", method = RequestMethod.POST)
    public  Map<String, Object> getAuFuncTrees(){
        Map<String, Object> resMap = new HashMap<String, Object>();
        SpecFunctionSource specFunctionSource = new SpecFunctionSource();
        specFunctionSource.setCode(AU_FUNC_TREE_ROOT_ID);
        List<SpecFunctionSource> saftList = funcTreeService.selectSpecByParentCodeForRoleAuth(specFunctionSource,null);
        resMap.put("success", true);
        resMap.put("resourceList", saftList);
        return resMap;
    }

    /**
     * ajax验证角色是否存在
     *
     * @return
     */
    @RequestMapping(value = "/isExistByName", method = RequestMethod.POST)
    public @ResponseBody
    boolean isExistByName(
            @RequestParam("name") String name,
            @RequestParam(value="functionSourceId",required=false) String functionSourceId) {
        return !funcTreeService.isExistByName(name, functionSourceId);
    }

    /**
     * ajax验证角色是否存在
     * @return
     */
    @RequestMapping(value = "/isExistByUrl",method = RequestMethod.POST)
    public @ResponseBody
    boolean validateField(@RequestParam(value="functionSourceId",required=false) String functionSourceId,
                          @RequestParam("sourceUrl") String sourceUrl) {
        if("/".equals(sourceUrl)){
            return true;
        }else {
            return !funcTreeService.isExistByUrl(sourceUrl, functionSourceId);
        }
    }

    /**
     * 验证数据
     * @param functionSource
     * @param resultMap
     * @return
     */
    private boolean validate(FunctionSource functionSource, Map<String, Object> resultMap){
        if(StringUtils.isBlank(functionSource.getSourceUrl())){
            resultMap.put("msg", "URl实际连接不能为空");
            return false;
        }
        if(StringUtils.isBlank(functionSource.getSourceName())){
            resultMap.put("msg", "资源名称不能为空");
            return false;
        }
        if(StringUtils.isBlank(functionSource.getParentCode())){
            resultMap.put("msg", "父节点不能为空");
            return false;
        }
        if(functionSource.getSourceType()!=null &&!("0").equals(functionSource.getSourceType())){
            functionSource.setIsLeaf("0");
        }else{
            functionSource.setIsLeaf("1");
        }
        functionSource.setSourceUrl(functionSource.getSourceUrl().trim());
        functionSource.setSourceName(functionSource.getSourceName().trim());

        if(funcTreeService.isExistByName(functionSource.getSourceName(), functionSource.getFunctionSourceId())){
            resultMap.put("msg", "资源名称已经存在");
            return false;
        }
        if("/".equals(functionSource.getSourceUrl()) && funcTreeService.isExistByName(functionSource.getSourceName(), functionSource.getFunctionSourceId())){
            resultMap.put("msg", "资源链接已经存在");
            return false;
        }
        return true;
    }


    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> add(FunctionSource functionSource){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Date currentDate = new Date();
        resultMap.put("isSuccess", false);
        if(!this.validate(functionSource, resultMap)){
            return resultMap;
        }
        funcTreeService.add(functionSource, currentDate);
        resultMap.put("isSuccess", true);
        resultMap.put("msg", "添加成功");
        return resultMap;
    }

    /**
     * 状态设置
     * @param functionSourceId 资源ID
     * @param enableStatus 启用/禁用状态
     * @return
     */
    @RequestMapping(value = "/modifyEnableStatus/{functionSourceId}/{enableStatus}", method = RequestMethod.POST)
    @ResponseBody
    public Map modifyEnableStatus(@PathVariable("functionSourceId")String functionSourceId, @PathVariable("enableStatus")String enableStatus) {
        Map<String, Object> result = new HashMap<>();
        final Date currentDate = new Date();
        logger.info("设置资源启用/禁用状态请求参数 资源id:{}, 状态：{}", new Object[]{functionSourceId, enableStatus});
        if(StringUtil.hasEmpty(functionSourceId, enableStatus) || !EnableStatusEnum.isValue(enableStatus)){
            result.put(IS_SUCCESS_DESC, false);
            result.put(MESSAGE_DESC, "参数错误");
            return result;
        }
        try {
            funcTreeService.modifyEnableStatus(functionSourceId, enableStatus);
            result.put(IS_SUCCESS_DESC, true);
            result.put(MESSAGE_DESC, "设置成功");
        }catch (Exception e){
            logger.error("设置资源启用/禁用状态失败，错误信息：{}", e.getMessage());
            result.put(IS_SUCCESS_DESC, false);
            result.put(MESSAGE_DESC,  "设置失败");
            return result;
        }
        return result;
    }


    @RequestMapping(value="/editUI/{functionSourceId}", method = RequestMethod.GET)
    public ModelAndView editUI(ModelAndView view, @PathVariable("functionSourceId")String functionSourceId){
        view.addObject("object", funcTreeService.selectByPrimaryKey(functionSourceId).get(0));
        view.setViewName("funcTree/edit");
        return view;
    }


    @RequestMapping(value="/edit", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> edit(FunctionSource functionSource){
        logger.info("编辑资源信息：{}", JsonUtil.objectToJson(functionSource));
        Date currentDate = new Date();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(IS_SUCCESS_DESC, false);
        if(!this.validate(functionSource, resultMap)){
            return resultMap;
        }
        try{
            funcTreeService.update(functionSource, currentDate);
            resultMap.put(IS_SUCCESS_DESC, true);
            resultMap.put(MESSAGE_DESC, "修改成功");
        }catch (Exception e){
            logger.error("编辑资源信息失败，错误信息：{}", e.getMessage());
            resultMap.put(IS_SUCCESS_DESC, false);
            resultMap.put(MESSAGE_DESC,  "设置失败");
            return resultMap;
        }
        return resultMap;
    }
}
